package com.ruoyi.generator.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.config.FileStorageProperties;
import com.ruoyi.generator.entity.*;
import com.ruoyi.generator.service.ManagementService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class FileUploadController {
    @Autowired
    private ManagementService managementService;

    @Autowired
    private FileStorageProperties fileStorageProperties;
    private final String uploadDir = "E:/fctextjavaworkspace/ruoyiUpload";
//    private final String uploadDir = "E:/fctextjavaworkspace/ruoyi/RuoYi-Vue-master/ruoyi-ui/src/assets/shengtaiImgs";
    private final String imagePath = "shengtaiImgs";

    @PostMapping("/api/common/upload")
    public ResponseEntity<Map<String, Object>> handleFileUpload(@RequestParam("file") MultipartFile[] files) {
        Map<String, Object> response = new HashMap<>();

        if (files.length == 0) {
            response.put("status", HttpStatus.BAD_REQUEST.value());
            response.put("message", "未选择文件");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                response.put("status", HttpStatus.BAD_REQUEST.value());
                response.put("message", "空文件: " + file.getOriginalFilename());
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }

            try {
                // 保存文件
                File uploadFile = new File(fileStorageProperties.getUploadDir(), file.getOriginalFilename());
                file.transferTo(uploadFile);

                // 添加文件路径到响应中，如果有需要的话
                response.put("fileUrl", fileStorageProperties.getUploadDir() + "/" + file.getOriginalFilename());  // 修改为你的文件实际访问路径
//                response.put("fileUrl",  imagePath+ "/" + file.getOriginalFilename());  // 修改为你的文件实际访问路径

            } catch (IOException e) {
                response.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.put("message", "上传失败: " + e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        }

        response.put("status", HttpStatus.OK.value());
        response.put("message", "文件上传成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/api/common/uploadPreparation")
    public ResponseEntity<Map<String, Object>> uploadPreparation(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "taskId", required = false) String taskId,
            @RequestParam(value = "uploadtype", required = false) String uploadtype) {

        Map<String, Object> response = new HashMap<>();
        // 文件校验
        if (file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        if (!StringUtils.hasText(fileName) ||
                !(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
            throw new ServiceException("仅支持Excel文件");
        }

        try {
            // 解析 Excel 文件
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            // 解析 Sheet 页 (区域表)
            Sheet areaSheet = workbook.getSheetAt(0);
            List<Region> regions = parseAreaSheet(areaSheet);
            // 解析 Sheet 页 (设备表)
            Sheet equipmentSheet = workbook.getSheetAt(1);
            List<Equipment> equipments = parseEquipmentSheet(equipmentSheet);
            // 解析 Sheet 页 (任务表)
            Sheet taskSheet = workbook.getSheetAt(2);
            List<Task> tasks = parseTaskSheet(taskSheet);
            // 解析 Sheet 页 (保养表)
            Sheet maintenancePlanSheet = workbook.getSheetAt(3);
            List<MaintenancePlan> maintenancePlanList = parseMaintenancePlanSheet(maintenancePlanSheet);

            workbook.close();
            managementService.performBatchOperations(regions, equipments, tasks,maintenancePlanList);
            response.put("status", HttpStatus.OK.value());
            response.put("message", "文件上传成功，数据已导入数据库");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            throw new ServiceException("文件解析失败: " + e.getMessage());
        }
    }

    private List<Region> parseAreaSheet(Sheet sheet) {
        List<Region> regions = new ArrayList<>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第1行开始（跳过表头）
            Row row = sheet.getRow(i);
            if (row == null) continue;
            Region region = new Region();
            region.setAreaId(getStringCellValue(row.getCell(0)));
            region.setAreaName(getStringCellValue(row.getCell(1)));
//            region.setAreaDescription(getStringCellValue(row.getCell(2)));
//            region.setRegion(getStringCellValue(row.getCell(3)));
//            region.setLongitude(Double.valueOf(getNumericCellValue(row.getCell(4))));
//            region.setLatitude(Double.valueOf(getNumericCellValue(row.getCell(5))));
            regions.add(region);
        }
        return regions;
    }

    private List<Equipment> parseEquipmentSheet(Sheet sheet) {
        List<Equipment> equipments = new ArrayList<>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            Equipment equipment = new Equipment();
            equipment.setEquipmentId(getStringCellValue(row.getCell(2)));
            equipment.setEquipmentName(getStringCellValue(row.getCell(1)));
            equipment.setEquipmentType(getStringCellValue(row.getCell(3)));
            equipment.setAreaId(getStringCellValue(row.getCell(0)));
//            equipment.setEquipmentDescription(getStringCellValue(row.getCell(4)));
//            equipment.setInstallationDate(getStringCellValue(row.getCell(5))); // 假设安装日期为字符串类型
//            equipment.setStatus(getStringCellValue(row.getCell(6)));
//            equipment.setIsDelete(getStringCellValue(row.getCell(7)));
            equipments.add(equipment);
        }
        return equipments;
    }
    private List<MaintenancePlan> parseMaintenancePlanSheet(Sheet sheet) {
        List<MaintenancePlan> maintenancePlanList = new ArrayList<>();
        int s=sheet.getLastRowNum();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;
            MaintenancePlan maintenancePlan = new MaintenancePlan();
            maintenancePlan.setEquipmentId(getStringCellValue(row.getCell(0)));
            maintenancePlan.setMaintenanceId(getStringCellValue(row.getCell(1)));
            maintenancePlan.setMaintenancePoint(getStringCellValue(row.getCell(2)));
            maintenancePlan.setMaintenanceItem(getStringCellValue(row.getCell(3)));
            maintenancePlan.setSetValue(getStringCellValue(row.getCell(4)));
//            task.setMaintenanceContent(getStringCellValue(row.getCell(2)));
//            task.setOperationalStatus(getStringCellValue(row.getCell(3)));
//            task.setCleanliness(Double.valueOf(getNumericCellValue(row.getCell(4))));
//            task.setTemperature(Double.valueOf(getNumericCellValue(row.getCell(5))));
//            task.setIsDelete(String.valueOf(getNumericCellValue(row.getCell(6))));
            maintenancePlanList.add(maintenancePlan);
        }
        return maintenancePlanList;
    }

    private List<Task> parseTaskSheet(Sheet sheet) {
        List<Task> tasks = new ArrayList<>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;
            Task task = new Task();
            task.setTaskId(getStringCellValue(row.getCell(1)));
            task.setEquipmentId(getStringCellValue(row.getCell(0)));
            task.setCheckPoint(getStringCellValue(row.getCell(2)));
            task.setCheckItem(getStringCellValue(row.getCell(3)));
            task.setSetValue(getStringCellValue(row.getCell(4)));
//            task.setMaintenanceContent(getStringCellValue(row.getCell(2)));
//            task.setOperationalStatus(getStringCellValue(row.getCell(3)));
//            task.setCleanliness(Double.valueOf(getNumericCellValue(row.getCell(4))));
//            task.setTemperature(Double.valueOf(getNumericCellValue(row.getCell(5))));
//            task.setIsDelete(String.valueOf(getNumericCellValue(row.getCell(6))));
            tasks.add(task);
        }
        return tasks;
    }

    // Helper methods to safely get cell values
    private Integer getNumericCellValue(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case NUMERIC:
                return (int) cell.getNumericCellValue();
            case STRING:
                // 如果单元格包含数字以字符串形式存储，则转换为整数
                try {
                    return Integer.valueOf(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    throw new ServiceException("单元格数据格式错误，无法转换为数字: " + cell.getStringCellValue());
                }
            default:
                throw new ServiceException("单元格类型错误：" + cell.getCellType());
        }
    }

    private String getStringCellValue(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            default:
                throw new ServiceException("单元格类型错误：" + cell.getCellType());
        }
    }

}